/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package testes;

import ccrClasses.layer1.results.Result;
import ccrClasses.layer1.results.Results;
import ccrClasses.layer2.Code;
import ccrClasses.layer2.CodingSystem;
import ccrClasses.layer2.DateTime;
import ccrClasses.layer2.Description;
import ccrClasses.layer2.ExactDateTime;
import ccrClasses.layer2.Test;
import ccrClasses.layer2.TestResult;
import ccrClasses.layer2.Text;
import ccrClasses.layer2.Type;
import ccrClasses.layer2.Value;
import ccrClasses.layer2.Version;
import com.google.gdata.client.GoogleService;
import com.google.gdata.client.Query;
import com.google.gdata.data.Entry;
import com.google.gdata.data.Feed;
import com.google.gdata.data.PlainTextConstruct;
import com.google.gdata.util.XmlBlob;
import health.entities.Paciente;
import health.persistence.PacienteDAO;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import parsers.GHXMLParser;
import parsers.SMXMLParser;
import smXmlMapping.Exame;
import smXmlMapping.Resultado;

/**
 *
 * @author matheus
 */
public class AuthSubTest {

    static final String FEED_BASE_PATH =
            "http://www.google.com/h9/feeds/";
    private static final String PROFILE_FEED_PATH = FEED_BASE_PATH + "profile/";
    private static final String REGISTER_FEED_PATH_REGISTER = FEED_BASE_PATH + "register/";
    static final String REGISTER_FEED_PATH = REGISTER_FEED_PATH_REGISTER + "default";
    private static final String PROFILE_LIST_URL_PATH = PROFILE_FEED_PATH + "list";
    static GoogleService h9Service;
    static PacienteDAO pacienteDAO;
    static Paciente paciente;

    public static void main(String args[]) {

        //testSendNotice();
        gatherTestNames(testReadProfile());
        //codificacao();
    }

    public static String testReadProfile() {

        h9Service = new GoogleService("weaver", "TCC_PEP");

        SMXMLParser smxmlp = new SMXMLParser("RES_21102009_1456_OS_10912695.xml");
        smxmlp.mapXmlFile();

        pacienteDAO = new PacienteDAO();

        paciente = pacienteDAO.resgatarPaciente(Integer.parseInt(smxmlp.parseUser().getPaciente()));

        h9Service.setAuthSubToken(paciente.getToken());
        h9Service.setAuthSubToken(paciente.getToken());
        String queryURL = "https://www.google.com/h9/feeds/profile/default/-/labtest?digest=true";

        Query query = null;
        try {
            query = new Query(new URL(queryURL));
//            Category myCategory = new Category("medication");
//            CategoryFilter myCategoryFilter = new CategoryFilter(myCategory);
//            query.addCategoryFilter(myCategoryFilter);
//             //Feed myCategoryResultsFeed = h9Service.query(query, Feed.class);
        } catch (IOException ex) {
            Logger.getLogger(AuthSubTest.class.getName()).log(Level.SEVERE, null, ex);
        }

        String xmlInString = "";
        try {
            Feed result = h9Service.query(query, Feed.class);
            //there should be only one entry that contains
            //the CCRg document for the profile.
//            if (result.getEntries().size() > 0) {
//                Entry firstMatchEntry = result.getEntries().get(0);
//                String myEntryTitle = firstMatchEntry.getTitle().getPlainText();
//                System.out.println(myEntryTitle);
//            }
            for (Entry entry : result.getEntries()) {
                xmlInString = xmlInString + prettifyXmlBlob(entry.getXmlBlob());
                //System.out.println(xmlInString);
            }

            return xmlInString = xmlInString.trim();

            //System.out.println(xmlInString);

        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;

//        GHXMLParser ghxmlp = new GHXMLParser();
//        try {
//            ghxmlp.mapXmlFile(new ByteArrayInputStream(xmlInString.getBytes("UTF-8")));
//        } catch (UnsupportedEncodingException ex) {
//            Logger.getLogger(AuthSubTest.class.getName()).log(Level.SEVERE, null, ex);
//            System.exit(1);
//        }
//
//        ArrayList<String> codes = ghxmlp.getResultCodes();
//        if (codes != null && codes.size() > 0) {
//            for (String s : codes) {
//                System.out.println(s);
//            }
//        }else{
//            JOptionPane.showMessageDialog(null, "Não há resultados de exames no GH.");
//        }
    }

    public static void testSendNotice() {

        h9Service = new GoogleService("weaver", "TCC_PEP");

        pacienteDAO = new PacienteDAO();

        Entry newNotice = new Entry();
        newNotice.setTitle(new PlainTextConstruct("Teste com authsub"));
        newNotice.setContent(new PlainTextConstruct("Nenhum:somente teste."));

        SMXMLParser smxmlp = new SMXMLParser("RES_21102009_1456_OS_10912695.xml");
        smxmlp.mapXmlFile();


        paciente = pacienteDAO.resgatarPaciente(Integer.parseInt(smxmlp.parseUser().getPaciente()));

        h9Service.setAuthSubToken(paciente.getToken());

        ArrayList<Exame> exames = smxmlp.extractExames();

        Exame exameTeste = exames.get(3);

        Results results = new Results();

        Result result = new Result();

        result.setDescription(new Description(new Text(exameTeste.getNome()),
                new Code(new Value(exameTeste.getDataResultado() + "#" + exameTeste.getCodigo()),
                new CodingSystem("TCC"), null)));
        result.setDateTime(new DateTime(new Type(new Text(Type.COLLECTION_START_DATE)), new ExactDateTime(formatData(exameTeste.getDataResultado()))));

        for (Resultado r : exameTeste.getResultados()) {
            Test t = new Test();
            t.setDescription(new Description(new Text(r.getAtributo())));
            t.setCollectionDateTime(new DateTime(new Type(new Text(Type.COLLECTION_START_DATE)), new ExactDateTime(formatData(exameTeste.getDataResultado()))));
            t.setTestResult(new TestResult(new Value(r.getResultado())));
            result.getTests().add(t);
        }

        results.getResults().add(result);

//        Test test = new Test();
//
//        Units units = new Units();
//        units.getUnit().add(new Unit("K/uL"));
//
//        Units units2 = new Units();
//        units2.getUnit().add(new Unit("90 - 100"));
//
//        test.setDescription(new Description(new Text("Glucose - Blood")));
//        test.setTestResult(new TestResult(new Value("98"), units));
//        //test.setNormalResult(new NormalResult(new Value("90 - 100"),units));
//        test.setNormalResult(new NormalResult(new Normal(new Description(new Text("90 - 100")))));
//        test.setCollectionDateTime(new DateTime(new Type(new Text(Type.COLLECTION_START_DATE)), new ExactDateTime("2007-02-21T07:00:00Z")));
//
//        test.setSource(new Source(new Actor(new ActorID("Jane Smith"),
//                new ActorRole(new Text(ActorRole.ORDERING)))));
//
//        result.getTests().add(test);
//
//        results.getResults().add(result);

        XmlBlob ccrgElement = new XmlBlob();
        ccrgElement.setBlob(results.constructCcrString());

        newNotice.setXmlBlob(ccrgElement);

        try {
            Entry createdNotice = h9Service.insert(new URL(REGISTER_FEED_PATH), newNotice);
        } catch (Exception e) {
        }
    }

    public static void codificacao() {
        try {
            String result = "Células Imaturas";
            String s1 = new String(result);
            String resultString = new String(s1.getBytes("UTF-8"), "ISO-8859-1");
            System.out.println(result);
            System.out.println(new String(resultString));
        } catch (UnsupportedEncodingException ex) {
            Logger.getLogger(AuthSubTest.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public static String prettifyXmlBlob(XmlBlob blob) throws TransformerException {


        String xmlString = blob.getBlob();

        StreamSource sourceXml = new StreamSource(new StringReader(xmlString));
        StringWriter sw = new StringWriter();

        TransformerFactory tf = TransformerFactory.newInstance();
        tf.setAttribute("indent-number", new Integer(2));
        Transformer trans;

        trans = tf.newTransformer();
        trans.setOutputProperty(OutputKeys.INDENT, "yes");
        trans.transform(sourceXml, new StreamResult(sw));
        xmlString = sw.toString();

        return xmlString;
    }

    private static String formatData(String xmlData) {
        String zuluData = new String();
        xmlData = xmlData.trim();
        String data = xmlData.substring(0, 10);
        String hora = xmlData.substring(10, 15);

        String dataDia = data.substring(0, 2);
        String dataMes = data.substring(3, 5);
        String dataAno = data.substring(6, 10);

        zuluData = dataAno + "-" + dataMes + "-" + dataDia + "T" + hora + ":00" + "Z";

        return zuluData;
    }

    private static void gatherTestNames(String xml) {
        ByteArrayInputStream is = null;
        try {
            is = new ByteArrayInputStream(xml.getBytes("UTF-8"));
            GHXMLParser ghxmlp = new GHXMLParser();
            ghxmlp.mapXmlFile(is);
            ArrayList<String> testNames = ghxmlp.getTestNames();
            for(String s : testNames){
                System.out.println(s);
            }
        } catch (UnsupportedEncodingException ex) {
            Logger.getLogger(AuthSubTest.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                is.close();
            } catch (IOException ex) {
                Logger.getLogger(AuthSubTest.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
}
